package com.kongchengji.zhanguafou.utils;
import com.alibaba.fastjson.JSONObject;
import com.kongchengji.zhanguafou.constant.WxInfo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class InfoByCodeUtil {
    static Logger logger = LoggerFactory.getLogger(InfoByCodeUtil.class);
    public static String getOpenId(String code)  {
//        1 第一步：通过code换取网页授权access_token  接口地址:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        Request request = new Request.Builder()
                              .url("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ WxInfo.APPID+"&secret="+WxInfo.APPSECRIPT+"&code="+code+"&grant_type=authorization_code")
                              .build();
        OkHttpClient client = new OkHttpClient();
        Response response;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            String openId = jsonObject.getString("openid");
            return openId;
        } catch (IOException e) {
            logger.error("网络出错");
        }
//        String accessToken = jsonObject.getString("access_token");
//      3 第三步：拉取用户信息(需scope为 snsapi_userinfo)
//        request = new Request.Builder()
//                .url(" https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN")
//                .build();
//        response = client.newCall(request).execute();
//        JSONObject userInfo = JSONObject.parseObject(response.body().string());
//        UserDO userDO = new UserDO();
//        userDO.setOpenId(userInfo.getString("openid"));
//        userDO.set
         return null;
    }
}
